package com.ukit.todolist_xml

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.TextView
import androidx.recyclerview.widget.AsyncListDiffer
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.ukit.todolist_xml.RoomRepository.ToDoItem

interface OnCheckBoxClickListener {
    fun onCheckBoxClick(position: Int, isChecked: Boolean)
}

class TodoListAdapter(private val onCheckBoxClickListener: MainActivity): RecyclerView.Adapter<TodoListAdapter.ViewHolder>() {
    private val diffUtilCallback: DiffUtil.ItemCallback<ToDoItem> = object : DiffUtil.ItemCallback<ToDoItem>(){
        override fun areItemsTheSame(oldItem: ToDoItem, newItem: ToDoItem): Boolean = oldItem === newItem

        override fun areContentsTheSame(oldItem: ToDoItem, newItem: ToDoItem): Boolean = oldItem == newItem
    }

    private  val asyncListDiffer = AsyncListDiffer(this, diffUtilCallback)

    fun setData(items: List<ToDoItem>){
        val newItems = items.toList()
        asyncListDiffer.submitList(newItems)
    }
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_todolist, parent, false)
        return  ViewHolder(view)
    }

    override fun getItemCount(): Int = asyncListDiffer.currentList.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val currentItem = asyncListDiffer.currentList[position]
        holder.info.text = currentItem.info
        holder.date.text = currentItem.date.toString()
        holder.completed.isChecked = currentItem.completed

        holder.completed.setOnCheckedChangeListener { buttonView, isChecked ->
            onCheckBoxClickListener.onCheckBoxClick(position, isChecked)
        }
    }

    class ViewHolder(itemView: View): RecyclerView.ViewHolder(itemView){
        val info = itemView.findViewById<TextView>(R.id.info)
        val date = itemView.findViewById<TextView>(R.id.addDate)
        val completed = itemView.findViewById<CheckBox>(R.id.completed)
    }


}
